﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary1 {
    //私有构造函数，静态构造函数，静态字段，readonly和const
    #region 版本1

    /*
    public sealed class Singleton {
        private static Singleton instance;
        private Singleton() { }
        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
        */

    #endregion

    #region 版本2

    /*
    public sealed class Singleton {
        private static readonly Singleton instance = new Singleton();
        private Singleton() { }
        public static Singleton Instance
        {
            get
            {
                return instance;
            }
        }
    }
        */

    #endregion

    #region 版本3

    /*
    public sealed class Singleton {
        private static volatile Singleton instance = null;
        private static object syncRoot = new object();
        private Singleton() { }
        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new Singleton();
                    }
                }
                return instance;
            }
        }
    }
        */

    #endregion

    #region 版本4

    /*
        public class Singleton {
        private static readonly Singleton _instance = new Singleton();
        private Singleton() { }
        public static Singleton Instance
        {
            get { return _instance; }
        }
        static Singleton() { }
    }
        */

    #endregion

    #region 版本5
    /*
        public sealed class Singleton {
        private Singleton() { }
        public static Singleton Instance
        {
            get { return Nested._instance; }
        }
        private class Nested {
            static Nested() { }
            internal static readonly Singleton _instance = new Singleton();
        }
    }
        */
    #endregion

    #region 版本6
    public class Singleton {
        private static readonly Lazy<Singleton> _instance = new Lazy<Singleton>(() => new Singleton());
        private Singleton() { }
        public static Singleton Instance
        {
            get { return _instance.Value; }
        }
    }

    #endregion
}
